package org.dei.perla.rockfall.gui;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

import org.dei.perla.rockfall.RockfallManager;

/**
 * JInternalFrame per eseguire il submit di una query
 */
public class QueryWindow extends JInternalFrame implements ActionListener{

	private static final long serialVersionUID = 8488836016707332137L;
	
	private static final String DEFAULT_TEXT = "SET acquisitionType=1, command=10, rs1=1, rs2=3, rs3=4, rs4=2, \ngx=68 , gy=69, gz=30, thupX=2, thupY=6, \nthupZ=8, thdwX=5, thdwY=78, thdwZ=9, \ntaps = NEW(CONSTANTVECTORINTEGER, \"3, 10, 5\") \nON 0";
	
	private final JTextPane textPane;
	private final RockfallManager manager;
	
	/**
	 * Costruttore
	 * @param manager RockfallManager per la gestione del sistema
	 */
	public QueryWindow(RockfallManager manager) {
		super("Query Window");
		setMaximizable(true);
		setIconifiable(true);
		setResizable(true);
		setClosable(false);
		
		this.manager = manager;
		
		getContentPane().setLayout(new GridBagLayout());
		GridBagConstraints gbc = new GridBagConstraints();
		textPane = new JTextPane();
		textPane.setText(DEFAULT_TEXT);
		JScrollPane scrollPane = new JScrollPane(textPane);
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.gridwidth = 3;
		gbc.weightx = 0.5;
		gbc.weighty = 0.5;
		gbc.fill = GridBagConstraints.BOTH;
		getContentPane().add(scrollPane, gbc);
		
		JButton button = new JButton("Cancel");
		button.setSize(new Dimension(100, 50));
		button.addActionListener(this);
		button.setActionCommand("cancel");
		gbc.gridx = 1;
		gbc.gridy = 1;
		gbc.weightx = 0;
		gbc.weighty = 0;
		gbc.gridwidth = 1;
		gbc.fill = GridBagConstraints.NONE;
		gbc.anchor = GridBagConstraints.LAST_LINE_END;
		getContentPane().add(button, gbc);
		
		button = new JButton("Execute");
		button.setSize(new Dimension(100, 50));
		button.addActionListener(this);
		button.setActionCommand("execute");
		gbc.gridx = 2;
		gbc.anchor = GridBagConstraints.LAST_LINE_START;
		getContentPane().add(button, gbc);
		
		pack();
		setSize(new Dimension(500, 300));
	}

	/**
	 * Metodo di implementazione ActionListener
	 */
	@Override
	public void actionPerformed(ActionEvent event) {
		
		if (event.getActionCommand().equals("cancel")) {
			
			textPane.setText(DEFAULT_TEXT);
			
		} else if (event.getActionCommand().equals("execute")) {
			
			manager.executeQuery(textPane.getText());
		}
	}
}
